<?php
class ViewSOFPAction extends CAction{

	/**
	 * note: true means credit is positive, false otherwise
	 */
	public $financialConfig=array(
		array(
			array(
				'label'=>'资产类',
				'category'=>1,
			),
			array(
				'label'=>'负债类',
				'category'=>2,
			),
		),
		array(
			array(
				'label'=>'流动资产',
				'category'=>array(11,12,13),
				'side'=>true
			),
			array(
				'label'=>'流动资产',
				'category'=>array(33,34,35),
			),
		),
		array(
			array(
				'category'=>11,
			),
			array(
				'category'=>33,
			),
		),
		array(
			array(
				'category'=>12,
			),
			array(
				'category'=>34,
			),
		),
		array(
			array(
				'category'=>13,
			),
			array(
				'category'=>35,
			),
		),
		array(
			array(
				'label'=>'资产总计',
				'category'=>1,
			),
			array(
				'label'=>'负债和所有者权益总计',
				'category'=>array(2,3,4),
			),
		),
	);

	public function run(){
		$viewSOFPModel = new ViewSOFPModel();
		$viewSOFPModel->unsetAttributes();
		$viewSOFPModel->endDate=date('Y-m-d');

		$financialData=false;
		if (isset($_GET['ViewSOFPModel'])) {
			$viewSOFPModel->attributes = $_GET['ViewSOFPModel'];
			if ($viewSOFPModel->validate()) {
				$financialData=$this->findFinancialData($viewSOFPModel);
			}
		}
		$this->getController()->render('viewSOFP',array(
			'viewSOFPModel'=>$viewSOFPModel,
			'financialData'=>$financialData,
			));
	}
	
	private function findFinancialData($viewSOFPModel){
		$baseCriteriaPrevious=new CDbCriteria();
		$baseCriteriaPrevious->compare('tokenDate', '<='.$viewSOFPModel->startDate);
		$baseCriteriaPrevious->compare('projectId', $viewSOFPModel->accountTokenProjectId);

		$baseCriteriaCurrent=new CDbCriteria();
		$baseCriteriaCurrent->compare('projectId', $viewSOFPModel->accountTokenProjectId);
		//$baseCriteriaCurrent->addBetweenCondition('tokenDate', $viewSOFPModel->startDate, $viewSOFPModel->endDate);
		$baseCriteriaCurrent->compare('tokenDate', '<'.$viewSOFPModel->endDate);
		
		$financialConfig=$this->financialConfig;
		$financialData=array();
		$commandBuilder = Yii::app()->db->getSchema()->getCommandBuilder();
		$itemModel=AccountTokenItem::model();
		foreach($financialConfig as $financialConfigRow){
			$financialDataRow=array();
			foreach($financialConfigRow as $financialConfigCell){
				
				if(isset($financialConfigCell['label'])){
					$label=$financialConfigCell['label'];
				}
				if(isset($financialConfigCell['category'])){
					$category=$financialConfigCell['category'];
					if(is_int($category)){
						$accountTokenCategory=AccountTokenCategory::model()->findByPk($category);
						$includeCategoryIds=CMap::mergeArray(
							preg_split('/[\|]+/', $accountTokenCategory->childrenCache, -1, PREG_SPLIT_NO_EMPTY),
							array(
								$category
							));
						if(!isset($financialConfigCell['label'])){
							$label=$accountTokenCategory->name;
						}
					}else{
						$findCategoryCriteria=new CDbCriteria();
						$findCategoryCriteria->addInCondition('id', $category);
						$includeCategoryIds=array_slice($category, 0);
						$accountTokenCategories=AccountTokenCategory::model()->findAll($findCategoryCriteria);
						foreach ($accountTokenCategories as $accountTokenCategory) {
							$includeCategoryIds=CMap::mergeArray(
								preg_split('/[\|]+/', $accountTokenCategory->childrenCache, -1, PREG_SPLIT_NO_EMPTY),
								$includeCategoryIds
								);
						}
						$includeCategoryIds=array_unique($includeCategoryIds);
					}
					
					$side=isset($financialConfigCell['side'])?$financialConfigCell['side']:true;
					
					$findCurrentSumCriteria=new CDbCriteria();
					$findCurrentSumCriteria->addInCondition('categoryId', $includeCategoryIds);
					$findCurrentSumCriteria->mergeWith($baseCriteriaCurrent);
					$findCurrentSumCriteria->join = 'INNER JOIN {{account_token}} as token on tokenId=token.id INNER JOIN {{account_token_category}} as category on categoryId=category.id';
					$findCurrentSumCriteria->select = 'sum(debit) as totalDebit, sum(credit) as totalCredit';
					$command = $commandBuilder->createFindCommand($itemModel->getTableSchema(), $findCurrentSumCriteria);
					$row = $command->queryRow();
					if($side){
						$currentValue=$row['totalCredit']-$row['totalDebit'];
					}else{
						$currentValue=$row['totalDebit']-$row['totalCredit'];
					}
					
					$findPreviousSumCriteria=new CDbCriteria();
					$findPreviousSumCriteria->addInCondition('categoryId', $includeCategoryIds);
					$findPreviousSumCriteria->mergeWith($baseCriteriaPrevious);
					$findPreviousSumCriteria->join = 'INNER JOIN {{account_token}} as token on tokenId=token.id INNER JOIN {{account_token_category}} as category on categoryId=category.id';
					$findPreviousSumCriteria->select = 'sum(debit) as totalDebit, sum(credit) as totalCredit';
					$command = $commandBuilder->createFindCommand($itemModel->getTableSchema(), $findPreviousSumCriteria);
					$row = $command->queryRow();
					if($side){
						$previousValue=$row['totalCredit']-$row['totalDebit'];
					}else{
						$previousValue=$row['totalDebit']-$row['totalCredit'];
					}
				}else{
					$previousValue=$currentValue=0;
				}
				$financialDataRow[]=$label;
				$financialDataRow[]=$previousValue;
				$financialDataRow[]=$currentValue;
			}
			$financialData[]=$financialDataRow;
		}
		return $financialData;
	}

}

class ViewSOFPModel extends CFormModel {
	public $accountTokenProjectId;
	public $startDate;
	public $endDate;
	
	public function attributeLabels(){
		return array(
			'accountTokenProjectId'=>'账本',
			'startDate'=>'日期',
			
		);
	}

	public function rules(){
		return array(
			array(
				'startDate, endDate, accountTokenProjectId',
				'required'
			),
			array(
				'startDate, endDate',
				'date',
				'format' => 'yyyy-MM-dd',
			),
		);
	}

}